import { useRequest } from 'ahooks';
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Button, Input, Form, Uploader, Selector, Radio, Space, Divider, Notify, Empty, Stepper, Toast, Sticky, NoticeBar, Switch } from 'react-vant';
import { getPayData, pushNote } from '../../api';
import lovesvg from '../../assets/love.svg';
import { VolumeO } from '@react-vant/icons';
import './index.less'

import { upload, wxPay } from '../../utils/utils';
import { baseUrl } from '../../utils/request';
const tags = ['旅行', '健身', '谈心', '可爱', '学生', '吃货', '微胖', '可见面', '找对象', '好相处', '一起看电影', '一起游戏', '外冷内热']
const tagList = tags.map(item => ({
    label: item,
    value: item
}));

type submitForm = {
    pushUserId: string,
    // 枚举类型
    sex: '1' | '0' | '-1',
    account: string,
    accountType: 'wx' | 'qq' | 'other',
    imageIds: string[],
    content: string
}

const SuccessPage = () => {
    const navigate = useNavigate()
    return (
        <Empty image={lovesvg} description={
            <Space direction="vertical" align='center'>
                <h3>恭喜您! 投递成功</h3>
                <p>纸条已进入CP池,可以被抽取啦!</p>
                {/* <p><small>3s后自动返回</small></p> */}
            </Space>
        }>
            <Space>
                <Button style={{ width: 120 }} size='small' plain round color='#3f72e6' onClick={() => { navigate('/') }}>
                    去抽一个
                </Button>
                <Button style={{ width: 120 }} size='small' plain round color='#f17783' onClick={() => { navigate('/records') }}>
                    查看记录
                </Button>
            </Space>
        </Empty>
    )
}

const PushNote = () => {
    const [isSuccess, setIsSuccess] = useState<Boolean>(false);
    const navigate = useNavigate();

    const submitPushNote = async (formData: any) => {

        let { data } = await getPayData({ orderType: 'pushNote' })

        if (data.status == 200) {
            // @ts-ignore
            wx.chooseWXPay({
                timestamp: data.timeStamp, // 支付签名时间戳，注意微信 jssdk 中的所有使用 timestamp 字段均为小写。但最新版的支付后台生成签名使用的 timeStamp 字段名需大写其中的 S 字符
                nonceStr: data.nonceStr, // 支付签名随机串，不长于 32 位
                package: data.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
                signType: 'RSA', // 微信支付V3的传入 RSA ,微信支付V2的传入格式与V2统一下单的签名格式保持一致
                paySign: data.paySign, // 支付签名
                complete: (res: any) => {
                    if (res.errMsg === 'chooseWXPay:ok') {
                        // 支付成功后的回调函数
                        Toast.success('支付成功')
                        pullNoteService({...formData,orderNo: data.orderNo})
                        // getNoteService({sex})
                    } else {
                        Toast.fail('支付失败')
                    }
                }
            });
        }
    }
    
    const pullNoteService = async (data: any) => {
        console.log(data);
        let params = null;
        if (data?.wxQrCode) {
            params = { ...data, sex: data.sex[0], wxQrCode: data?.wxQrCode[0]?.url }
        } else {
            params = { ...data, sex: data.sex[0], wxQrCode:'' }
        }
        params.orderNo = 'nopay'  //todo
        await pushNote(params);
        Notify.show({
            type: 'success',
            message: '投递成功！您可以取抽取一个纸条'
        })
        setIsSuccess(true)
    }

    const qrCodeUpload = async (file: any) => {
        console.log(file);

        return {url:file.remoteUrl}
    }

    const beforeUnload = async (file: any, files: File[]) => {

        try {
            Toast.loading({
                message: '上传中...',
                duration: 0
            });

            const body = new FormData()
            body.append('files', file)
            const resp = await fetch(baseUrl + "/wxqrcodeOcr", {
              headers: {
                "authorization": `Bearer ${sessionStorage.getItem('token')}`,
              },
              method: 'POST',
              body,
            })
            const res = await resp.json()
            console.log(res);
            let isWchatQrCode = res.data.qrCode?.includes('https://u.wechat.com/')
            if (!isWchatQrCode) {
                Toast.fail('您上传的不是微信二维码哦!')
                return false
            }
            file.remoteUrl = res.data.url
            Toast.success('上传成功!')
            return file;

          } catch (error) {
            Toast.fail('上传失败!')
            return false
          }

        // try {
        //     // let url = window.webkitURL.createObjectURL(file) || window.URL.createObjectURL(file);
        //     // console.log(url);
        //     const qr = new QrCode()
        //     let qrCodeRes = await qr.decodeFromImage("http://clf-blind-box.oss-cn-hangzhou.aliyuncs.com/notePics/40aeafdc1c65dba1846bad202.jpeg")
        //     console.log(qrCodeRes);

        //     let isWchatQrCode = qrCodeRes?.data?.includes('https://u.wechat.com/')
        //     if (!isWchatQrCode) {
        //         Toast.fail('您上传的不是微信二维码!')
        //         return false
        //     }
        //     return file
        // } catch (error) {
        //     alert(JSON.stringify(error))
        //     return false
        // }

    }

    const { loading, run } = useRequest(pullNoteService, { manual: true, throttleWait: 3000 });

    const [form] = Form.useForm();
    const accountType = Form.useWatch('accountType', form);

    if (isSuccess) {
        return <SuccessPage />
    } else {
        return (
            <>
                <NoticeBar
                    leftIcon={<VolumeO />}
                    text="如果发现投递信息有误，平台会取消您的投递，并定时清除您的信息，请您真实填写！"
                />
                <Form
                    style={{ paddingBottom: 20 }}
                    form={form}
                    onFinish={run}
                    footer={
                        <div style={{ margin: '16px 16px 0' }}>
                            <Button loading={loading} round nativeType="submit" type="primary" block>
                                立即投递
                            </Button>
                        </div>
                    }
                >
                    <Divider contentPosition='left' style={{ color: '#999', borderColor: '#3f45ff' }}>
                        投一张让她/他抽到后主动联系我
                    </Divider>
                    <Form.Item labelWidth='40' name="sex" label="我是" initialValue={['1']} rules={[{ required: true }]}>
                        <Selector
                            options={[
                                { label: '男生', value: '0' },
                                { label: '女生', value: '1' }
                            ]}
                        />
                    </Form.Item>
                    <Form.Item labelWidth='40' name="accountType" label="给你" initialValue="wx" rules={[{ required: true, message: '请填写账号类型' }]}>
                        <Radio.Group>
                            <Space>
                                <Radio name="wx">微信号</Radio>
                                <Radio name="qq">QQ号</Radio>
                                <Radio name="other">其他<small>(需备注)</small></Radio>
                            </Space>
                        </Radio.Group>
                    </Form.Item>


                    {accountType === 'wx' && (
                        <Form.Item
                            labelWidth='40'
                            name='wxQrCode'
                            intro={<div className='desTip'>
                                <p>为了确保数据真实性,请上传微信二维码</p>
                                <p>平台会对您的二维码进行检测</p>
                                <p>图片大小请控制在3M以内</p>
                            </div>}
                            label='WX二维码'
                            rules={[{ required: true, message: '请选择微信二维码' }]}
                            initialValue={[]}
                        >
                            <Uploader maxCount={1} previewSize={80} uploadText='微信二维码' maxSize={3 * 1024 * 1024} upload={qrCodeUpload} beforeRead={beforeUnload} />
                        </Form.Item>
                    )}


                    <Form.Item
                        labelWidth='40'
                        rules={[{ required: accountType === 'wx' ? false : true, message: '请填写/微信号/QQ号' }]}
                        name="account"
                        label="账号"
                    >
                        <Input placeholder="如有微信二维码可不填" />
                    </Form.Item>


                    <Form.Item labelWidth='40' rules={[{ required: true }]} name="age" label="年龄" initialValue={20}>
                        <Stepper min={14} max={50} />
                    </Form.Item>

                    <Form.Item labelWidth='40' rules={[{ required: true }]} name="height" label="身高" initialValue={175}>
                        <Stepper min={155} max={200} />
                    </Form.Item>

                    <Form.Item
                        labelWidth='40'
                        name='imageIds'
                        label='照片'
                        rules={[{ required: true, message: '请选择照片/可传多张' }]}
                        initialValue={[]}
                    >
                        <Uploader upload={upload} previewSize={80} uploadText='头像/生活照' maxSize={3 * 1024 * 1024} />
                    </Form.Item>
                    <Form.Item labelWidth='40' name="tags" rules={[{ required: true, message: '至少选一个吧' }]} label="标签" initialValue={['找对象']}>
                        <Selector
                            className='tagsWrapper'
                            options={tagList}
                            multiple={true}
                        />
                    </Form.Item>
                    <Form.Item labelWidth='40' name="recommend" label="推荐">
                        <Switch activeValue={'1'} inactiveValue={'0'} />
                    </Form.Item>
                    <Form.Item labelWidth='40' name='content' label='留言'>
                        <Input.TextArea rows={2} autoSize maxLength={120} placeholder="可填写您的兴趣爱好或想对她/他说的话" showWordLimit />
                    </Form.Item>
                </Form>
            </>
        );
    }
};

export default PushNote;
